package com.example.lin.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.example.lin.common.R;
import com.example.lin.entity.vo.LoginUser;
import com.example.lin.entity.vo.TokenVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/token")
public class TokenController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取当前token信息
     * @return R
     */
    @PreAuthorize("hasAuthority('sys:token:info')")
    @PostMapping("/info")
    public R info() {
        return R.ok(new TokenVo(StpUtil.getTokenValue(), StpUtil.getTokenTimeout()));
    }

    /**
     * 刷新token
     * @return R
     */
    @PreAuthorize("hasAuthority('sys:token:refresh')")
    @PostMapping("/refresh")
    public R refresh(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            return R.error("token为空");
        }
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (ObjectUtils.isEmpty(loginUser)) {
            return R.error("用户不存在");
        }
        StpUtil.login(loginUser.getUsername());
        redisTemplate.opsForValue().set("username:" + loginUser.getUsername(), StpUtil.getTokenValue(), StpUtil.getTokenTimeout());
        return R.ok(new TokenVo(StpUtil.getTokenValue(), StpUtil.getTokenTimeout())).setMsg("token刷新成功");
    }
}
